var loading_more = false; //正在加载
var loading_filter = null;
var first_load = true;
var active_item = null,clone_item = null;
var current_focus_img;
function insertHtml(html){
    if(active_item){
        $(active_item).after(html);
    }
    else{
        $('article#main').append(html);
    }
}
//替换选中文本内容，参数text为要替换的内容
function repaceSelectionText(html) {
    //非IE浏览器
    if (window.getSelection) {
        var sel = window.getSelection();
        var range = sel.getRangeAt(0); //即使已经执行了deleteFromDocument(), 这个函数仍然返回一个有效对象.
        if(range.startContainer){ // DOM下
            sel.deleteFromDocument(); //清除选择的内容
            sel.removeAllRanges(); // 删除Selection中的所有Range
            range.deleteContents(); // 清除Range中的内容

            var frag = document.createDocumentFragment();
             var el = document.createElement("div");
            el.innerHTML = html; 
            node = el.firstChild
            while (node) { //node.nodeType!=1
                lastNode = frag.appendChild(node);
                node = node.nextSibling;
            }
            range.insertNode(frag);
            if (lastNode) {
                range = range.cloneRange();
                range.endContainer = lastNode;
                range.startContainer = lastNode;
                range.startOffset = 0;
                range.endOffset = 0;
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
            return;
            // 获得Range中的第一个html结点
            var container = range.startContainer;
            // 获得Range起点的位移
            var pos = range.startOffset;
            // 建一个空Range
            var new_range = document.createRange();
            // 插入内容
            console.log(container.nodeType);
            if(container.nodeType == 3){// 如是一个TextNode
                //var cons = win.document.createTextNode(",:),");
                // container.insertData(pos, cons.nodeValue);
                //$(container).after(html);
                container.insertData(pos, html);
                // 改变光标位置
                // new_range.setEnd(container, pos + cons.nodeValue.length);
                // new_range.setStart(container, pos + cons.nodeValue.length);
            }else{// 如果是一个HTML Node
                var afternode = container.childNodes[pos];
                $(afternode).insertBefore(html);
                //container.insertBefore(cons, afternode);
                // new_range.setEnd(cons, cons.nodeValue.length);
                // new_range.setStart(cons, cons.nodeValue.length);
            }
            //sel.addRange(new_range);
        }
        // var h1 = document.createElement('H1'); //生成一个插入对象
        // h1.innerHTML = "text"; //设置这个对象的内容
        // range.insertNode(h1); //把对象插入到选区, 这个操作不会替换选择的内容, 而是追加到选区的后面, 所以如果需要普通粘贴的替换效果, 之前执行deleteFromDocument()函数.
    }
    else if (document.selection && document.selection.createRange) {
        //IE浏览器
        var sel = document.selection.createRange(); //获得选区对象
        sel.pasteHTML(html); //粘贴到选区的html内容, 会替换选择的内容.
    }
}
function insertSelectionText(html) {
    if(document.selection && document.selection.createRange) {
          document.selection.createRange().pasteHTML(html);
    }else{
        var selection = window.getSelection();
        var range;
        if (selection)
        {
        range = selection.getRangeAt(0);
        }else {
        range = iframeDocument.createRange();
        }
        var oFragment = range.createContextualFragment(html),
        oLastNode = oFragment.lastChild ;
        range.insertNode(oFragment) ;
        range.setEndAfter(oLastNode ) ;
        range.setStartAfter(oLastNode );
        selection.removeAllRanges();//清除选择
        selection.addRange(range);
    }
}
function loadStyles( page ,filter ){
        jQuery('#load-more-style').before('<div id="loading-style" style="margin:10px;color:red;text-align:center;"><img src="http://static.135editor.com/img/ajax/circle_ball.gif"> </div>');
        
//      console.log( me.options.page_url +'&inajax=1&page='+page+'&filter='+filter );
        
        jQuery.ajax({
            async:true, 
            type:'get',
            url: '/editor_styles/open_styles?inajax=1&inajax=1&page='+page+'&filter='+filter,
            success: function (data){
                
                jQuery('#style-overflow-list #loading-style').remove();
                
                if( first_load ) {
                    jQuery('#style-overflow-list').html(data);
                    jQuery('#style-overflow-list').scrollTop(0);
                    jQuery('#style-categories .active').removeClass('active');
                    jQuery('#style-categories .filter').data('page',null).data('status',null);
                    jQuery('#style-categories').removeAttr('data-status').data('page',2);
                    first_load = false;
                }
                else{
                    // jQuery('#load-more-style').remove();
                    var newStyles = jQuery('<div>'+data+'</div>').find('.editor-template-list > li');
                    
                    if(newStyles.size() > 0) {
                        var append_nums = 0;
                        newStyles.each(function() {
                            var $this = jQuery(this);
                            $this.addClass('mix').css({'display':'block'});
                            
                            if( jQuery('#style-overflow-list').find( "#"+$this.attr('id') ).size() == 0) {
                                append_nums ++ ;
                                jQuery('.editor-template-list').append( $this );
                                
                            }
                        });
                        loadedStyles();
                        
                        if(append_nums == 0) { loading_more = false;return true; }; //没有更多了                 
                    }
                    else{
                        loading_filter.attr('data-status','done');                  
                        loading_more = false;
                        return true; // 没有更多了
                    }
                }
                
                loading_more = false; // 正在加载状态结束，待内容都置入页面之后。
                loadedStyles();
            },
            dataType:"html"
        });
    }

    function loadedStyles(){
        var obj_id = '#mp-styles';
        setTimeout(function(){
            jQuery( obj_id +' img.lazy').lazyload({
                effect: "fadeIn",
                container: obj_id +' #style-overflow-list',
                data_attribute:'src',
                threshold : 50,
                failure_limit:50
            });
            jQuery( obj_id +'#style-overflow-list' ).trigger('scroll');
        },500);
    }
    function loadTpl(){
        if( $('#mp-templates').size() > 0 ) {
            if( $('#mp-templates').css('display')!='none' ) {
                $('#mp-templates').modal('hide');
            }
            else{
                publishController.open_html_dialog('mp-templates');
            }
        }
        else{
            publishController.open_dialog('/editor_styles/systemTemplates?inajax=1&v=page',{
                'id':'mp-templates',
                'title':'系统模板',
                'callback':function(obj){
                    // adapter/editor.js  <div id="##_sidebar" class="%%-sidebar">
                    
                    //jQuery(container).find('.edui-editor-sidebar').css('height',height);
                    
                    // obj.find('.editor-menus').height( height );
                    // obj.find('#editor-styles-content').css('height',height);
                    var height = $(window).height();
                    obj.find('.modal-body').css('max-height',height-60);
                    
                    /* 点击模板时加载模板内容 */
                    jQuery(obj).on('click','#system-template-list .insert-tpl-content',function(){              
                        var template_id = jQuery(this).data('id');  
                        var article = $('article.article135');
                        article.html( jQuery('#template-'+template_id).html() );
                        publishController.close_dialog();
                    });

                    jQuery(obj).on('click','#system-template-list .template-cover',function(){              
                        var template_id = jQuery(this).data('id');              
                        ajaxAction(PLAT135_URL+'/editor_styles/view/'+template_id+'.json?nolazy=1',null,null,function(request){
                            if(request.data) {
                                var article = $('article.article135');
                                article.html( request.data.EditorStyle.content );                        
                            }
                        });             
                    });
                }
            });
        }
    }
    function refreshStyle( ){


        var width = jQuery(window).width();
        if( $('#mp-styles').size() > 0 ) {
            if( $('#mp-styles').css('display')!='none' ) {
                $('#mp-styles').modal('hide');
            }
            else{
                publishController.open_html_dialog('mp-styles');
            }
        }
        else{
            publishController.open_dialog('/editor_styles/open?inajax=1&v=page',{
                'id':'mp-styles',
                'callback':function(obj){
                    // adapter/editor.js  <div id="##_sidebar" class="%%-sidebar">
                    
                    //jQuery(container).find('.edui-editor-sidebar').css('height',height);
                    
                    // obj.find('.editor-menus').height( height );
                    // obj.find('#editor-styles-content').css('height',height);
                    var height = $(window).height();
                    obj.find('.modal-body').css('max-height',height-60)
                    obj.find('#style-overflow-list').height( height-110 );
                    
                    // obj.find('#styleSearchResultList').height( height - jQuery('#copyright',obj).height() -45 ); //减去标题栏与版权信息及搜索框的高度
                    
                    jQuery('#style-categories >li',obj).hover(function(){
                        jQuery(this).addClass('open');
                    },function(){
                        jQuery(this).removeClass('open');
                    });
                    
                    jQuery(document).on('click','#style-categories .filter',function(){
                        
                        jQuery('.editor-template-list > li',obj).hide();//.fadeOut('slow','linear');
                        jQuery(jQuery(this).attr('data-filter'),obj).show();//.fadeIn('slow','linear');
                        
                        jQuery('#style-categories .filter',obj).removeClass('active');
                        jQuery(this).addClass('active');
                        
                        obj.find('#style-overflow-list').trigger('scroll').scrollTop(0);
                    });   
                    
                    
                    
                    jQuery('#style-overflow-list',obj).on('scroll',function(){

                        if( !loading_more && jQuery('#load-more-style').size() == 1 && jQuery('#load-more-style').position().top < jQuery('#style-overflow-list').height() + 150 ) {
                            
                            
                            if( jQuery('#style-categories a.active:first',obj).size() > 0 ) {
                                loading_filter = jQuery('#style-categories a.active:first');    
                                
                                if(loading_filter && loading_filter.attr('data-status') ) {
                                    return true;
                                }
                                var page = loading_filter.data('page');
                                if( !page || typeof(page) == 'undefined' ) { page = 1;}
                                loading_more = true;
                                loadStyles( page , loading_filter.data('filter') );
                                loading_filter.data('page', parseInt(page) + 1);
                            }
                            else{
                                loading_filter = jQuery('#style-categories',obj);
                                if(loading_filter && loading_filter.attr('data-status') == 'done' ) {
                                    return true;
                                }
                                var page = loading_filter.data('page');
                                if( !page || typeof(page) == 'undefined' ) { page = 1;}
                                loading_more = true;
                                loadStyles( page );
                                loading_filter.data('page',parseInt(page)+1);
                            }
                        }
                        return true;
                    }).trigger('scroll');
                    
                    
                    jQuery(obj).on('click','#editor-styles .editor-menus li',function(){
                        
                        jQuery(this).parent().find('li').removeClass('active'); //取消之前激活的选项
                        jQuery(this).parent().next('.tab-content').find('.tab-pane').removeClass('active'); // 取消之前显示的选项内容
                        
                        jQuery(jQuery(this).find('a').attr('href'),obj).addClass('active'); // 显示对应的选项内容            
                        jQuery(this).addClass('active'); 
                        
                        var anchor = jQuery(this).find('a:first');
                        var target = anchor.attr('href');
                        if(anchor.data('target')){
                            target = anchor.data('target');
                        }
                        
                        function tab_loaded(){

                            jQuery('.open-tpl-brush',target).attr('class','open-tpl-brush');
                            jQuery('.insert-tpl-content',target).attr('class','insert-tpl-content');
                            
                            jQuery(target).find('a').click(function(){  
                                var url = jQuery(this).attr('href');
                                if(url.search(/\?/)!=-1){
                                    url+='&inajax=1';
                                }
                                else{
                                    url+='?inajax=1';
                                }
                                if(jQuery(this).attr('id') =='btn-search-image') {
                                    url += '&name='+encodeURI(jQuery('#SearchImageName',target).val());
                                }
                                
                                var re = /^#/;
                                if( typeof(jQuery(this).attr('onclick')) != "undefined" || jQuery(this).attr('target') =='_blank' || typeof(url) == "undefined" || re.test(url) || url.substr(0,10).toLowerCase()=='javascript'){
                                    return true; // 当为锚点，javascript,或者定义了onclick 时，忽略动作
                                    // 可以使用onclick="return true;"或者target="_selft"来忽略dialog中链接的绑定事件
                                }
                                jQuery(target).parent().scrollTop(0);
                                jQuery(target).prepend('<section style="position:absolute;z-index:100;color: red;width:100%;height:100%;background-color:rgba(0,0,0,0.5);padding:10px;"><img src="http://static.135editor.com/img/ajax/circle_ball.gif"> '+me.getLang("labelMap.isLoading")+'</section>');
                                jQuery(target).load(url,function(){ tab_loaded();});                            
                                return false;
                            });
                        }
                        
                        if(jQuery(target).html() == "" || jQuery(anchor).data('refresh') == "always") { // 没有内容，或者设置了每次都刷新      
                            if(anchor.data('url')) {
                                jQuery(target).html('<section style="padding:10px;"><img src="http://static.135editor.com/img/ajax/circle_ball.gif"> '+me.getLang("labelMap.isLoading")+'</section>');
                                jQuery(target).load(anchor.data('url'),function(){
                                    tab_loaded();
                                });
                            }
                        }
                        
                        return false;
                    }); 
                    
                    jQuery(obj).on('click','#online-styles .col-sm-12,#user-style-list .col-sm-12,#style-overflow-list .ui-portlet-list > li,#styleSearchResultList #style_search_list > ul > li',function(){
                        //data-135editor=\"true\"
                        //多插入一个空行，防止有时无法选择到底部了，或者两个元素中间不方便插入内容。
                        
                        if(jQuery(this).hasClass('ignore')){
                            return false;
                        }
                        
                        var ret = false;
                        var num = parseInt(jQuery(this).find('.autonum:first').text());
                        
                        var id = jQuery(this).data('id');
                        
                        
                        jQuery(this).contents().filter(function() {
                            return this.nodeType === 3 && jQuery.trim(jQuery(this).text()) == "";
                        }).remove();
                        jQuery(this).find('p').each(function(){
                            if(jQuery.trim(jQuery(this).html())=="&nbsp;") {
                                jQuery(this).html('<br/>');
                            }
                        });
                        jQuery(this).find('.135editor').attr('class','_135editor');
                        jQuery(this).find('*').each(function(){
                            if(jQuery(this).attr('data-width')) {
                                return;
                            }
                        
                            if( this.style.width && this.style.width != "" ) {
                                jQuery(this).attr('data-width',this.style.width);
                            }
                        });
                        
                        var style_item = jQuery(this).find('> ._135editor:first'); //第一级的
                        
                        if(style_item.size()){
                            if(style_item.find('> *').size() == 1 && style_item.find('> *').eq(0).hasClass('135editor') ) {
                                // 只包含一个一级子元素，且为135样式。说明代码本身包含了135editor的class标记，只需要插入即可，无需再增加外围代码。
                                ret = insertHtml( style_item.html() );
                            }
                            else{
                                var html = style_item.prop('outerHTML');
                                ret = insertHtml( html ); 
                            }
                        }
                        else{ //最外围包装135editor容器
                            ret = insertHtml("<section data-id=\""+id+"\" class=\"_135editor\">" + jQuery(this).html() + "</section>"); 
                        }
        
                        if(ret){
                            style_click(id);                    
                            if(typeof num != "undefined") {
                                jQuery(this).find('.autonum:first').text(num+1);
                            }
                        }
                        publishController.close_dialog();
                    });
                    
                    jQuery(obj).on('click','.changeStyles',function(){
                        var type = jQuery(this).data('type');
                        if( type == 'opennew' ){
                            if( me.options.page_url.indexOf('type=opennew') > 0 ) {
                                return;
                            }
                            else{
                                jQuery('#style-categories a.active').removeClass('active');
                                me.options.page_url += '&type=opennew';
                                $('#style-overflow-list .editor-template-list').remove();
                                jQuery('#style-categories',obj).data('page',1);
                                first_load = true;//loadStyles( 1 );
                                jQuery('#style-overflow-list',obj).trigger('scroll');
                            }
                        }
                        else if( me.options.page_url.indexOf('type=opennew') > 0 ) {
                            jQuery('#style-categories a.active').removeClass('active');
                            me.options.page_url = me.options.page_url.replace('&type=opennew','');
                            $('#style-overflow-list .editor-template-list').remove();
                            jQuery('#style-categories',obj).data('page',1);
                            first_load = true;//loadStyles( 1 );
                            jQuery('#style-overflow-list',obj).trigger('scroll');
                        }
                        //console.log(me.options.page_url);
                    })
                }
            });
        }
    };


$(function(){

    var winHeight = $(window).height();  
    $(window).resize(function(){  
        if( $(window).height() == winHeight ){
            $('#toolbar').show();$('#fix-footer').show();
        }
        else{
            $('#toolbar').hide();$('#fix-footer').hide();
        }
    });  
    
    // $(document).on('click','article img',function(e){
    //     current_focus_img = this;     console.log("ccc");   
    // })
    $(document).on('dblclick','article img',function(e){
        current_focus_img = this;
        $('#uploadImage').trigger('click');
        //console.log("dblclick"); //图片双击换图
        return false;
    });

    $(document).on('click','article ._135editor',function(){
        if(active_item != this) {
            $(active_item).removeClass('active').find('.tool-border').remove();
            $(this).find('[contenteditable]').removeAttr('contenteditable');
            active_item = this;
            $(this).addClass('active').append('<section class="tool-border" style="z-index:100;"><section style="position: absolute; border-top:1px dashed red; width: 100%; top: -2px; "></section><section style="position: absolute; border-top:1px dashed red; width: 100%; bottom: -2px; "></section><section style="position: absolute; border-top:1px dashed red; width: 5px; top: -2px; left: -5px; "></section><section style="position: absolute; border-top:1px dashed red; width: 5px; top: -2px; right: -5px; "></section><section style="position: absolute; border-top:1px dashed red; width: 5px; bottom: -2px; left: -5px; "></section><section style="position: absolute; border-top:1px dashed red; width: 5px; bottom: -2px; right: -5px; "></section><section style="position: absolute; border-left:1px dashed red; height: 100%; top:0;left: -5px; "></section><section style="position: absolute; border-right:1px dashed red;height: 100%; right: -5px;top:0;"></section><section style="position: absolute; border-left:1px dashed red; height: 5px; bottom: -2px; left: -5px; "></section><section style="position: absolute; border-left:1px dashed red; height: 5px; top: -2px; left: -5px; "></section><section style="position: absolute; border-left:1px dashed red; height: 5px; bottom: -2px; right: -5px; "></section><section style="position: absolute; border-left:1px dashed red; height: 5px; top: -2px; right: -5px; "></section></section>');
        }
        
        if($(this).find('[contenteditable]').size() == 0) {            
            //loopDom(this);
        }
        //$(this).find('.135brush').attr('contenteditable',true);
        //console.log($(this).html());  
        function loopDom(obj){
            $(obj).find('.tool-border .change-btn').remove();
            $(obj).contents().each(function(){
                if(this.nodeType == 1 && !$(this).hasClass('tool-border') ) {
                    loopDom(this);
                }
                else if(this.nodeType == 3){
                    var $this = this;
                    if($.trim(this.nodeValue)==""){
                        return; //空节点跳过。不能返回false，否则跳过后部节点的执行
                    }
                    /*var offset = $(this.parentNode).position();
                    if(!this.previousSibling){
                        var cobj = $('<section style="left:'+offset.left+'px;top:'+offset.top+'px;" class="change-btn">换字</section>');
                        cobj.click(function(){
                            console.log($this);
                            return false;
                        });
                        cobj.appendTo( $(this).parents('._135editor:first').find('.tool-border') );
                    }
                    else if(this.previousSibling){
                        var left = offset.left + $(this.previousSibling).width();
                        var top = offset.top + $(this.previousSibling).height();
                        var cobj = $('<section style="left:'+left+'px;top:'+top+'px;" class="change-btn">换字</section>');
                        cobj.click(function(){
                            console.log($this);
                            return false;
                        });
                        cobj.appendTo( $(this).parents('._135editor:first').find('.tool-border') );
                    }*/
                    var range = document.createRange();
                    range.selectNodeContents($this);
                    var rects = range.getClientRects();
                    console.log($this);console.log(rects);
                    if(rects.length > 0) {
                        var poffset = $(this).parents('._135editor:first').offset();
                        var left = rects[0].left;
                        var top = rects[0].top + $(window).scrollTop()- poffset.top;
                        var cobj = $('<section style="left:'+left+'px;top:'+top+'px;" class="change-btn">换字</section>');
                        cobj.click(function(){
                            var sel = window.getSelection();
                            var range = document.createRange();
                            range.selectNodeContents($this);
                            sel.addRange(range);
                            // console.log($this);
                            publishController.open_html_dialog('edit-textnode');
                            $('#edit-textnode textarea').height($(window).height()-120).val($this.nodeValue);
                            $('#edit-textnode').find('.btn-confirm').unbind().click(function(){
                                $this.nodeValue = $('#edit-textnode textarea').val();

                                // $($this).parent('._135editor:first').trigger('click');
                                loopDom(active_item);
                                publishController.close_dialog();
                            })
                            return false;
                        });

                        cobj.appendTo( $(this).parents('._135editor:first').find('.tool-border') );
                    }
                }
            })
        }
        
        return false;
    });
    $(document).on('dblclick','article ._135editor',function(){
        function loopDom(obj){
            $(obj).contents().each(function(){
                if(this.nodeType == 1 && !$(this).hasClass('tool-border') ) {
                    loopDom(this);
                }
                else if(this.nodeType == 3){
                    var $this = this;
                    if($.trim(this.nodeValue)==""){
                        return; //空节点跳过。不能返回false，否则跳过后部节点的执行
                    }
                    if( $(this).parents('.135brush:first').size() > 0){
                        $(this).parents('.135brush:first').attr('contenteditable',true);
                    }
                    else{
                        var pp = $(this).parents('p:first');
                        if( pp.size() > 0 && pp.find('._135editor').size() == 0 ) {
                            pp.attr('contenteditable',true);
                        }
                        else{
                            $(this.parentNode).attr('contenteditable',true);
                        }
                    }                    
                }
            })
        }
        loopDom(this);
        $(this).find('.change-btn').remove();
    });
    $('#toolbar #moveUp').click(function(){
        if(active_item) {
            var prev = $(active_item).prev();
            if(prev && prev.size() > 0) {
                $(active_item).insertBefore(prev);
            }
        }
    });
    $('#toolbar #moveDown').click(function(){
        if(active_item) {
            var next = $(active_item).next();
            if(next && next.size() > 0) {
                $(active_item).insertAfter(next);
            }
        }
    });
    $('#toolbar #delete').click(function(){
        if(active_item) {
            $(active_item).remove();
        }
    });
    $('#toolbar #copy').click(function(){
        if(active_item) {
            clone_item = $(active_item).clone();
            clone_item.removeClass('active').find('.tool-border').remove();
            showSuccessMessage('已成功复制',null,1000);
        }
        else{
            showErrorMessage('没有选中样式',null,1000);
        }
    });
    $('#toolbar #insert-copy').click(function(){
        if(clone_item) {
            $(active_item).after(clone_item.clone());
        }
        else{
            showErrorMessage('请先复制样式后点插入',null,1000);
        }
    });

    $('#toolbar #afterBlank').click(function(){
        if(active_item) {
            var blank = $('<section data-role="paragraph" contenteditable="true" class="_135editor active" style="border: 0px none; padding: 0px;"><p><br/></p></section>');
            blank.insertAfter(active_item);
            blank.trigger('click').focus();
        }
    });
    $('#toolbar #beforeBlank').click(function(){
        if(active_item) {
            var blank = $('<section data-role="paragraph" contenteditable="true" class="_135editor active" style="border: 0px none; padding: 0px;"><p><br/></p></section>');
            blank.insertBefore(active_item);
            blank.trigger('click').focus();            
        }
    });
    $('#toolbar #focusBlank').click(function(){
        if(active_item) {
            var blank_html = '<section id="new-focus-blank" data-role="paragraph" contenteditable="true" class="_135editor active" style="border: 0px none; padding: 0px;"><p><br/></p></section>';
            repaceSelectionText(blank_html);
            $('#new-focus-blank').trigger('click').focus().removeAttr('id');            
        }
    });
    
    $('#op-styles').click(function(){
        refreshStyle();
    });
    $('#op-templates').click(function(){
        loadTpl();
    });
})
